package com.ujs.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujs.commonutils.constant.RedisKey;
import com.ujs.commonutils.utils.JwtUtils;
import com.ujs.commonutils.utils.MD5;
import com.ujs.servicebase.exception.GuliException;
import com.ujs.ucenter.entity.Member;
import com.ujs.ucenter.entity.vo.RegisterVo;
import com.ujs.ucenter.mapper.MemberMapper;
import com.ujs.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-08-11
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void register(RegisterVo registerVo) {
        // 获取注册的数据
        String code = registerVo.getCode(); // 验证码
        String email = registerVo.getEmail(); // 邮箱
        String nickname = registerVo.getNickname();
        String password = registerVo.getPassword();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickname) || StringUtils.isEmpty(code)) {
            throw new GuliException(20001, "注册失败，");
        }

        // 校验code
        String redisCode = redisTemplate.opsForValue().get(RedisKey.KEY_EMAIL_CODE + email);
        if (!code.equals(redisCode)) {
            throw new GuliException(20001, "注册失败，验证码错误");
        }
        // 判断邮箱是否重复
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>().eq("email", email);
        Integer count = baseMapper.selectCount(wrapper);
        if (count != 0) {
            throw new GuliException(20001, "注册失败，存在相同邮箱");
        }
        // 添加到数据库
        Member member = new Member();
        BeanUtils.copyProperties(registerVo, member);
        member.setPassword(MD5.encrypt(password));
        member.setIsDisabled(false);
        member.setAvatar("https://c-ssl.duitang.com/uploads/item/201810/18/20181018162952_qhgsh.jpeg");
        baseMapper.insert(member);
        // 删除验证码
        redisTemplate.delete(RedisKey.KEY_EMAIL_CODE + email);
    }

    /**
     * 用户登录
     *
     * @param member
     * @return
     */
    @Override
    public String login(Member member) {
        // 获取登录手机号和密码
        String email = member.getEmail();
        String password = member.getPassword();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            throw new GuliException(20001, "登录失败，手机号或密码为空");
        }
        // 判断手机号是否正确
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>().eq("email", email);
        Member mobileMember = baseMapper.selectOne(wrapper);
        if (mobileMember == null) {
            throw new GuliException(20001, "登录失败，邮箱不存在");
        }
        // 判断密码
        if (!MD5.encrypt(password).equals(mobileMember.getPassword())) {
            throw new GuliException(20001, "登录失败，密码错误");
        }
        // 判断用户是否禁用
        if (mobileMember.getIsDisabled()) {
            throw new GuliException(20001, "登录失败，用户已被禁用");
        }
        // 登录成功  按照规则，使用jwt工具类生成token
        return JwtUtils.getJwtToken(mobileMember.getId(), mobileMember.getNickname());
    }

    @Override
    public Member getMemberInfo(HttpServletRequest request) {
        // 调用jwt工具类的方法。根据request对象的头信息，获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (!StringUtils.isEmpty(memberId)) {
            // 查询数据库，获取用户信息
            return baseMapper.selectById(memberId);
        } else {
            throw new GuliException(20001, "请先登录！");
        }
    }

    @Override
    public Member getOpenIdMember(String openid) {
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>().eq("openid", openid);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Member getMemberInfoById(String memberId) {
        System.out.println("memberId===>" + memberId);
        return baseMapper.selectById(memberId);
    }

    @Override
    public Integer countRegister(String day) {
        return baseMapper.countRegister(day);
    }
}
